package com.quick.develop.flowable.framework.cmd.admin;

import com.quick.develop.flowable.constant.BpmConstants;
import com.quick.develop.flowable.enums.BpmExecuteCmd;
import com.quick.develop.flowable.framework.enums.istance.BpmProcessInstanceDeleteReasonEnum;
import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.runtime.ProcessInstance;

import java.io.Serializable;
import java.util.Optional;

import static com.quick.develop.flowable.enums.BpmErrorCodeConstants.PROCESS_INSTANCE_CANCEL_FAIL_NOT_EXISTS;
import static com.quick.develop.framework.common.utils.ServiceExceptionUtils.exception;


/**
 * @author junyuan.liu
 * @description:
 * @date 2022/9/20 13:28
 */
public class CancelProcessCmd implements Command<Void>, Serializable {
    private static final long serialVersionUID = 7908823551536660547L;
    
    protected String processInstanceId;
    protected String businessKey;
    
    public CancelProcessCmd(String processInstanceId) {
        this.processInstanceId = processInstanceId;
    }

    @Override
    public Void execute(CommandContext commandContext) {
        ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
        RuntimeService runtimeService = processEngineConfiguration.getRuntimeService();
        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        Optional.ofNullable(instance).orElseThrow(() -> exception(PROCESS_INSTANCE_CANCEL_FAIL_NOT_EXISTS));
        //设置标识
        runtimeService.setVariable(processInstanceId, BpmConstants.EXECUTE_CMD, BpmExecuteCmd.STOP.cmd);

        runtimeService.deleteProcessInstance(processInstanceId,
                BpmConstants.ADMIN_STOP +BpmConstants.COMMENT_SEPARATOR +
                        BpmProcessInstanceDeleteReasonEnum.ADMIN_CANCEL_TASK);

        return null;
    }
    
}
